package com.qnbc.mystery.service.impl;

import java.math.BigDecimal;
import java.util.*;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qnbc.mystery.domain.*;
import com.qnbc.mystery.pojo.domain.*;
import com.qnbc.mystery.pojo.param.BoxAddOrderParam;
import com.qnbc.mystery.service.*;
import com.qnbc.mystery.utils.DateUtils;
import com.qnbc.mystery.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.qnbc.mystery.mapper.BoxProductMapper;

/**
 * 奖盒关联商品Service业务层处理
 *
 * @author guzj
 * @date 2024-01-30
 */
@Service
public class BoxProductServiceImpl extends ServiceImpl<BoxProductMapper, BoxProduct> implements IBoxProductService {
    @Autowired
    private BoxProductMapper boxProductMapper;

    @Autowired
    private ICartService cartService;

    @Autowired
    private IBoxSetService boxSetService;
    @Autowired
    private IWinRecordService winRecordService;
    @Autowired
    private IProductSwiperImageService productSwiperImageService;
    @Autowired
    private IFoodOrderService foodOrderService;
    @Autowired
    private IOrderDetailService orderDetailService;

    /**
     * 查询奖盒关联商品
     *
     * @param id 奖盒关联商品主键
     * @return 奖盒关联商品
     */
    @Override
    public BoxProduct selectBoxProductById(Long id) {
        return boxProductMapper.selectBoxProductById(id);
    }

    /**
     * 查询奖盒关联商品列表
     *
     * @param boxProduct 奖盒关联商品
     * @return 奖盒关联商品
     */
    @Override
    public List<BoxProduct> selectBoxProductList(BoxProduct boxProduct) {
        return boxProductMapper.selectBoxProductList(boxProduct);
    }


    /**
     * 修改奖盒关联商品
     *
     * @param boxProduct 奖盒关联商品
     * @return 结果
     */
    @Override
    public int updateBoxProduct(BoxProduct boxProduct) {
        return boxProductMapper.updateBoxProduct(boxProduct);
    }

    /**
     * 批量删除奖盒关联商品
     *
     * @param ids 需要删除的奖盒关联商品主键
     * @return 结果
     */
    @Override
    public int deleteBoxProductByIds(Long[] ids) {
        return boxProductMapper.deleteBoxProductByIds(ids);
    }

    /**
     * 删除奖盒关联商品信息
     *
     * @param id 奖盒关联商品主键
     * @return 结果
     */
    @Override
    public int deleteBoxProductById(Long id) {
        return boxProductMapper.deleteBoxProductById(id);
    }

    @Override
    public Long mlsAddOrder(BoxAddOrderParam boxAddOrderParam) {
        User currentUser = TokenUtils.getCurrentUser();


        List<ProductSwiperImage> boxProducts = productSwiperImageService.list(new LambdaQueryWrapper<ProductSwiperImage>().eq(ProductSwiperImage::getProductid, boxAddOrderParam.getBoxId()));

        BoxSet boxSet = new BoxSet();
        boxSet.setBoxType(2);
        List<BoxSet> boxSets = boxSetService.selectBoxSetList(boxSet);

        Map<String, Double> categoryProbabilities = new HashMap<>();
        Map<String, Integer> categoryQuantities = new HashMap<>();
        for (ProductSwiperImage boxProduct : boxProducts) {
            BoxSet boxSet1 = boxSets.stream().filter(item -> item.getBoxName().equals(boxProduct.getName())).findFirst().get();

            categoryProbabilities.put(boxProduct.getId() + "", boxSet1.getWinLv()); // 设置种类1的中奖概率
            categoryQuantities.put(boxProduct.getId() + "", Math.toIntExact(boxSet1.getNum())); // 设置种类1的数量
        }

        SingleWinnerLottery lottery = new SingleWinnerLottery(categoryProbabilities, categoryQuantities);

        int numberOfPrizes = Integer.parseInt(boxAddOrderParam.getNumberOfPrizes()); // 设置抽奖次数
        System.out.println("Congratulations to the winners:");

        //创建订单
        FoodOrder foodOrder = new FoodOrder();
        foodOrder.setCreatedTime(new Date());
        foodOrder.setUpdatedTime(new Date());
        foodOrder.setCreatedBy(String.valueOf(currentUser.getId()));
        foodOrder.setOrderNo(DateUtils.getCurrentDateStr());//订单id格式用DateUtil
        foodOrder.setCreatedTime(new Date());//添加创建日期属性
        foodOrder.setStatus(3);//添加创建日期属性
        foodOrder.setTotalprice(new BigDecimal(0));//添加创建日期属性
        foodOrder.setOrderType("2");//添加创建日期属性
        boolean save = foodOrderService.save(foodOrder);

        //加入购物车  存储每个盒子id  一个盒子一条订单
        List<Cart> carts = new ArrayList<>();
        for (int i = 0; i < numberOfPrizes; i++) {
            String winner = lottery.drawWinner();
            if (winner != null) {
                System.out.println("魔力赏抽奖" + winner);
                Optional<ProductSwiperImage> first = boxProducts.stream().filter(item -> item.getId().toString().equals(winner)).findFirst();
                if (first.isPresent()) {
                    ProductSwiperImage productSwiperImage = first.get();
                    Cart cart = new Cart();
                    cart.setProductId(String.valueOf(productSwiperImage.getProductid()));
                    cart.setProductDetialId(winner);
                    cart.setNum(numberOfPrizes);
                    cart.setCartType(2);
                    cart.setCreatedBy(String.valueOf(currentUser.getId()));
                    cart.setCreatedTime(new Date());
                    cart.setOrderNo(String.valueOf(foodOrder.getId()));
                    carts.add(cart);

                    OrderDetail orderDetail = new OrderDetail();
                    orderDetail.setGoodsid(Long.valueOf(winner));
                    orderDetail.setGoodsDetialId(Long.valueOf(winner));
                    orderDetail.setGoodsname(productSwiperImage.getName());
                    orderDetail.setGoodspic(productSwiperImage.getImage());
                    orderDetail.setGoodsnumber(1L);
                    orderDetail.setGoodsprice(productSwiperImage.getProPrice());
                    orderDetail.setGoodsDetialName(productSwiperImage.getName());
                    orderDetail.setMid(foodOrder.getId());
                    orderDetailService.save(orderDetail);
                }
            } else {
                System.out.println("No winner for this draw.");
            }
        }
        cartService.saveBatch(carts);
        return foodOrder.getId();
    }

    @Override
    public Boolean payNotify() {
        return true;
    }


    /**
     * 一番赏
     *
     * @param boxAddOrderParam
     * @return
     */
    @Override
    public Long yfsAddOrder(BoxAddOrderParam boxAddOrderParam) {
        User currentUser = TokenUtils.getCurrentUser();

        List<ProductSwiperImage> boxProducts = productSwiperImageService.list(new LambdaQueryWrapper<ProductSwiperImage>().eq(ProductSwiperImage::getProductid, boxAddOrderParam.getBoxId()));

        BoxSet boxSet = new BoxSet();
        boxSet.setBoxType(1);
        List<BoxSet> boxSets = boxSetService.selectBoxSetList(boxSet);

        List<ItemPrize> items = new ArrayList<>();
        for (ProductSwiperImage boxProduct : boxProducts) {
            BoxSet boxSet1 = boxSets.stream().filter(item -> item.getBoxName().equals(boxProduct.getName())).findFirst().get();
            items.add(new ItemPrize(boxProduct.getId().toString(), boxSet1.getWinLv(), Math.toIntExact(boxProduct.getSort())));
        }

        MultiPrizeLottery lottery = new MultiPrizeLottery(items);

        int numberOfPrizes = 0;
        if (!boxAddOrderParam.getNumberOfPrizes().equals("all")) {
            numberOfPrizes = Integer.parseInt(boxAddOrderParam.getNumberOfPrizes());
        } else {
            numberOfPrizes = boxProducts.stream().mapToInt(ProductSwiperImage::getResidueStock).sum();

        }
        // 设置抽奖的个数 1 3 5 全收
        List<String> winners = lottery.drawWinners(numberOfPrizes);

        //创建订单
        FoodOrder foodOrder = new FoodOrder();
        foodOrder.setCreatedTime(new Date());
        foodOrder.setUpdatedTime(new Date());
        foodOrder.setTotalprice(new BigDecimal(0));
        foodOrder.setCreatedBy(String.valueOf(currentUser.getId()));
        foodOrder.setOrderNo(DateUtils.getCurrentDateStr());//订单id格式用DateUtil
        foodOrder.setCreatedTime(new Date());//添加创建日期属性
        foodOrder.setStatus(3);//添加创建日期属性
        foodOrder.setOrderType("2");//添加创建日期属性
        boolean save = foodOrderService.save(foodOrder);


        System.out.println("Congratulations to the winners:");
        //加入购物车  存储每个盒子id  一个盒子一条订单
        List<Cart> carts = new ArrayList<>();
        for (String winner : winners) {
            Optional<ProductSwiperImage> first = boxProducts.stream().filter(item -> item.getId().toString().equals(winner)).findFirst();
            if (first.isPresent()) {
                ProductSwiperImage productSwiperImage = first.get();
                Cart cart = new Cart();
                cart.setProductId(String.valueOf(productSwiperImage.getProductid()));
                cart.setProductDetialId(winner);
                cart.setNum(numberOfPrizes);
                cart.setCartType(2);
                cart.setCreatedBy(String.valueOf(currentUser.getId()));
                cart.setCreatedTime(new Date());
                cart.setOrderNo(String.valueOf(foodOrder.getId()));
                carts.add(cart);

                WinRecord winRecord = new WinRecord();
                winRecord.setGoodsid(Long.valueOf(winner));
                winRecord.setGoodsname(productSwiperImage.getName());
                winRecord.setCreatedBy(String.valueOf(currentUser.getId()));
                winRecord.setUserName(currentUser.getUsername());
                winRecord.setCreatedTime(new Date());
                winRecordService.insertWinRecord(winRecord);


                OrderDetail orderDetail = new OrderDetail();
                orderDetail.setGoodsid(Long.valueOf(winner));
                orderDetail.setGoodsDetialId(Long.valueOf(winner));
                orderDetail.setGoodsname(productSwiperImage.getName());
                orderDetail.setGoodspic(productSwiperImage.getImage());
                orderDetail.setGoodsnumber(1L);
                orderDetail.setGoodsprice(productSwiperImage.getProPrice());
                orderDetail.setGoodsDetialName(productSwiperImage.getName());
                orderDetail.setMid(foodOrder.getId());
                orderDetailService.save(orderDetail);
            }
        }
        cartService.saveBatch(carts);
        return foodOrder.getId();
    }
}
